import { Model, Effect } from "dva-core-ts";
import { Reducer } from "redux";
import {
  CategoryUnionType,
  getCategory,
  getCategorySuccess,
  GET_CATEGORY,
  GET_CATEGORY_SUCCESS,
} from "./action";
import { Category } from "./dto";
import { handleGetCategoryApi } from "./service";

export interface CategoryState {
  category: {
    loaded: boolean;
    success: boolean;
    result: Array<Category>;
  };
}
const initialState: CategoryState = {
  category: {
    loaded: false,
    success: false,
    result: [],
  },
};
//这里就简写了，完整写法看auth模块
const categoryModel = {
  namespace: "category",
  state: initialState,
  reducers: {
    setState(state = initialState, { payload }: any) {
      switch (payload.type) {
        case GET_CATEGORY:
          return {
            ...state,
            category: {
              loaded: false,
              success: false,
              result: [],
            },
          };
        case GET_CATEGORY_SUCCESS:
          return {
            ...state,
            category: {
              loaded: true,
              success: true,
              result: payload.payload,
            },
          };
        default:
          return {
            ...state,
          };
      }
    },
  },
  effects: {
    *handleGetCategory({ payload }: any, { call, put }: any) {
      yield put({
        type: "setState",
        payload: getCategory(),
      });
      //@ts-ignore
      let response = yield call(handleGetCategoryApi, payload);
      console.log("handleGetCategory", response);
      yield put({
        type: "setState",
        payload: getCategorySuccess(response.data),
      });
    },
  },
};

export default categoryModel;
